package rpc.sync;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import javax.management.RuntimeErrorException;

public class Request {
	
	/**回调id**/
	public int id;
	/**自增分配id**/
	private static final AtomicInteger increid = new AtomicInteger(0);
	
	private static final ThreadLocal<ReentrantLock> locks = new ThreadLocal<>();
	private static final ThreadLocal<Condition> conditions = new ThreadLocal<>();
	
	private int timeOut;
	
	private ReentrantLock l;
	private Condition c;
	private Object body;
	
	
	public Request(int timeOut)
	{
		id = increid.incrementAndGet();
		l = locks.get();
		c = conditions.get();
		if(l==null)
		{
			l = new ReentrantLock(false);
			c= l.newCondition();
			locks.set(l);
			conditions.set(c);
		}
		this.timeOut = timeOut;
	}
	
	public void waitFor()
	{
		l.lock();
		try {
//			synchronized (this) {
			c.await(timeOut,TimeUnit.MILLISECONDS);
			//TODO 检测回调是否回来
			
//				wait();
//			}
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}finally
		{
			l.unlock();
		}
	}
	
	
	public void unWait()
	{
//		synchronized (this) {
		try {
			l.lock();
			c.signal();
//			notify();
		} finally{
			l.unlock();
		}
//		}
	}
	

	public Object getBody() {
		return body;
	}

	public void setBody(Object body) {
		this.body = body;
	}

	public int getId() {
		return id;
	}
}
